package com.xayy.health.mgt.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xayy.health.core.antlr4.utils.FunUtil;
import com.xayy.health.core.antlr4.utils.Golabl;
import com.xayy.health.mgt.mapper.AssessParmaMapper;
import com.xayy.health.mgt.model.AssessParma;
import com.xayy.health.mgt.model.SatelliteCode;
import com.xayy.health.mgt.model.vo.AssessParmaVo;
import com.xayy.health.mgt.service.AssessParmaService;
import com.xayy.health.mgt.service.SatelliteCodeService;

import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.base.utils.annotation.DataTable;
import cn.kawins.mybatis.base.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

/**
 * @author Nie
 * @version v1.0
 * @date 2022-05-31 14:14
 */
@Service
public class AssessParmaServiceImpl extends BaseServiceImpl<AssessParma> implements AssessParmaService {
    @Autowired
    private SatelliteCodeService satelliteCodeService;
    @Resource
    private AssessParmaMapper assessParmaMapper;

    /**
     * 新增配置管理健康评估模型
     *
     * @param assessParma
     *            入参
     * @return 结果日志
     */
    @Override
    public CheckResult<Object> insertAssessParma(AssessParma assessParma, Boolean isDefault) {
        CheckResult<?> checkResult = checkName(false, assessParma);
        if (checkResult.no()) {
            return CheckResult.fail(checkResult.getCheckMsg());
        }
        SatelliteCode satelliteCode = satelliteCodeService
            .selectOne(SatelliteCode.builder().satelliteId(String.valueOf(assessParma.getSatId())).build());
        if (BeanUtil.isEmpty(satelliteCode)) {
            return CheckResult.fail("卫星code不存在");
        }
        CheckResult<?> checkSyntax = FunUtil.checkSyntax(assessParma.getVisitor(), satelliteCode.getSatelliteCode());
        // 清除缓存信息
        Golabl.clearXn(satelliteCode.getSatelliteCode());
        Golabl.clear(satelliteCode.getSatelliteCode());
        if (checkSyntax.no()) {
            return CheckResult.fail(checkSyntax.getCheckMsg());
        }
        if (isDefault.equals(Boolean.FALSE)) {
            // 修改默认计算模型
            AssessParma assessDb = assessParmaMapper.selectDefaultAssessParma(assessParma.getSatId(),
                assessParma.getSystemId(), assessParma.getComponentId());
            assessDb.setDefaultCalculate(false);
            updateById(assessDb);
        }
        insert(assessParma);
        return CheckResult.success();
    }

    /**
     * 删除配置管理健康评估模型
     *
     * @param id
     *            健康评估管理id
     * @return 结果日志
     */
    @Override
    public CheckResult<Object> deleteAssessParma(Long id) {
        deleteById(id);
        return CheckResult.success();
    }

    /**
     * 修改配置管理健康评估模型
     *
     * @param assessParma
     *            入参
     * @return 结果日志
     */
    @Override
    public CheckResult<Object> updateAssessParma(AssessParma assessParma, Boolean isDefault) {
        CheckResult<?> checkResult = checkName(true, assessParma);
        if (checkResult.no()) {
            return CheckResult.fail(checkResult.getCheckMsg());
        }
        SatelliteCode satelliteCode = satelliteCodeService
            .selectOne(SatelliteCode.builder().satelliteId(String.valueOf(assessParma.getSatId())).build());
        if (BeanUtil.isEmpty(satelliteCode)) {
            return CheckResult.fail("卫星code不存在");
        }
        CheckResult<?> checkSyntax = FunUtil.checkSyntax(assessParma.getVisitor(), satelliteCode.getSatelliteCode());
        // 清除缓存信息
        Golabl.clearXn(satelliteCode.getSatelliteCode());
        Golabl.clear(satelliteCode.getSatelliteCode());
        if (checkSyntax.no()) {
            return CheckResult.fail(checkSyntax.getCheckMsg());
        }
        if (isDefault.equals(Boolean.FALSE)) {
            // 修改默认计算模型
            AssessParma assessDb = assessParmaMapper.selectDefaultAssessParma(assessParma.getSatId(),
                assessParma.getSystemId(), assessParma.getComponentId());
            assessDb.setDefaultCalculate(false);
            updateById(assessDb);
        }
        updateById(assessParma);
        return CheckResult.success();
    }

    /**
     * 根据卫星id，分系统id，设备id获取部件健康评估模型列表
     *
     * @param map
     *            入参
     * @return 评估模型列表
     */
    @Override
    @DataTable(value = "selectAssessParma")
    public List<AssessParma> selectAssessParma(Map<String, Object> map) {
        return assessParmaMapper.selectPage(map.get("satId"), map.get("sysId"), map.get("comId"));
    }

    /**
     * 查询健康评估模型信息
     *
     * @param id
     *            健康评估模型id
     * @return 结果日志
     */
    @Override
    public CheckResult<Object> selectAssessModel(Long id) {
        return CheckResult.success(selectById(id));
    }

    /**
     * 性能评分获取部件评估模型列表
     *
     * @param satId
     *            卫星id
     * @param nodeId
     *            节点id
     * @return CheckResult<List < AssessParam>>
     */
    @Override
    public CheckResult<List<AssessParma>> getAssessParmaListBySat(Long satId, Long systemId, Long nodeId) {
        List<AssessParma> assessParams = assessParmaMapper.selectListById(Boolean.FALSE,
            AssessParma.builder().satId(satId).systemId(systemId).componentId(nodeId).build());
        return CheckResult.success(assessParams);
    }

    @Override
    public CheckResult<Object> selectAssessParmaBySat(Long satId) {
        List<AssessParmaVo> select = assessParmaMapper.selectAssessParmaBySat(satId);
        return CheckResult.success(select);
    }

    @Override
    public CheckResult<Object> checkAssessParma(AssessParma assessParma) {
        if (assessParma.getId() == null) {
            // 新增
            CheckResult<Object> checkInfo = checkInfo(Boolean.FALSE, assessParma);
            if (checkInfo.no()) {
                return checkInfo;
            }
            return insertAssessParma(assessParma, true);
        } else {
            // 更新
            CheckResult<Object> checkInfo = checkInfo(Boolean.TRUE, assessParma);
            if (checkInfo.no()) {
                return checkInfo;
            }
            return updateAssessParma(assessParma, true);
        }
    }

    /**
     * 校验名称是否重复
     *
     * @param isUpdate
     *            是否是更新
     * @param assessParma
     *            入参
     * @return CheckResult<?>
     */
    private CheckResult<?> checkName(Boolean isUpdate, AssessParma assessParma) {
        Example example = new Example(AssessParma.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("satId", assessParma.getSatId());
        criteria.andEqualTo("assessName", assessParma.getAssessName());
        if (Boolean.TRUE.equals(isUpdate)) {
            criteria.andNotEqualTo("id", assessParma.getId());
        }
        int i = selectCountByExample(example);
        if (i > 0) {
            return CheckResult.fail("评估模型名称：" + assessParma.getAssessName() + "已存在");
        }
        Example exampleCode = new Example(AssessParma.class);
        Example.Criteria criteriaCode = exampleCode.createCriteria();
        criteriaCode.andEqualTo("satId", assessParma.getSatId());
        criteriaCode.andEqualTo("assessCode", assessParma.getAssessCode());
        if (Boolean.TRUE.equals(isUpdate)) {
            criteriaCode.andNotEqualTo("id", assessParma.getId());
        }
        int m = selectCountByExample(exampleCode);
        if (m > 0) {
            return CheckResult.fail("评估模型Code：" + assessParma.getAssessCode() + "已存在");
        }
        return CheckResult.success();

    }

    private CheckResult<Object> checkInfo(Boolean isUpdate, AssessParma assessParma) {
        if (null == assessParma.getDefaultCalculate()) {
            assessParma.setDefaultCalculate(false);
            return CheckResult.success();
        }
        if (assessParma.getDefaultCalculate().equals(Boolean.TRUE)) {

            List<AssessParma> assessParams = assessParmaMapper.selectListById(isUpdate, assessParma);
            if (CollUtil.isNotEmpty(assessParams)) {
                return CheckResult.fail(10010, "评估模型：" + assessParams.get(0).getAssessName() + "已被设为默认计算模型，是否替换");
            }
        }
        return CheckResult.success();
    }

}
